package com.kylewang.pomodoro.ui.my;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bytedance.scene.group.GroupScene;
import com.google.firebase.firestore.DocumentReference;
import com.kylewang.pomodoro.MainActivity;
import com.kylewang.pomodoro.R;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.kylewang.pomodoro.helper.DBManager;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


public class MyScene extends GroupScene implements View.OnClickListener, Observer {

    private FirebaseUser me;

    @NonNull
    @Override
    public ViewGroup onCreateView(@NonNull LayoutInflater layoutInflater, @NonNull ViewGroup viewGroup, @Nullable Bundle bundle) {
        ViewGroup mRootView = (ViewGroup) layoutInflater.inflate(R.layout.fragment_my, viewGroup, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        MainActivity mainActivity = (MainActivity) getActivity();
        me = FirebaseAuth.getInstance().getCurrentUser();
        if (me != null) {
            updateLoginStatus(true);
        }
        mainActivity.registerSubscribeAuthEvents(this);
        int[] rids = new int[] { R.id.btn_login, R.id.btn_logout, R.id.buttonsetting, R.id.buttonfeedback, R.id.buttonhelp };
        for (int rid: rids) {
            View subv = findViewById(rid);
            subv.setOnClickListener(this);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    private void updateLoginStatus(Boolean login) {
        View loginedView = findViewById(R.id.logined_view);
        View notLoginView = findViewById(R.id.not_login_view);
        if (login) {
            loginedView.setVisibility(View.VISIBLE);
            notLoginView.setVisibility(View.INVISIBLE);
            Button userinfo = (Button)findViewById(R.id.btn_userinfo);
            userinfo.setText(me.getDisplayName());
        } else {
            loginedView.setVisibility(View.INVISIBLE);
            notLoginView.setVisibility(View.VISIBLE);
        }
    }

    public void onClick(View view) {
        MainActivity main = ((MainActivity)getActivity());
        switch (view.getId()) {
            case R.id.btn_login:
                main.login();
                break;
            case R.id.btn_logout:
                main.logout();
                break;
            case R.id.buttonsetting:
                String[] itmes = new String[] { "Auto", "Day", "Night" };
                new MaterialDialog.Builder(this.getSceneContext())
                        .title(R.string.theme_setting)
                        .items(itmes)
                        .itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                main.getDelegate().setLocalNightMode(which);
                                main.recreate();
                                return true;
                            }
                        })
                        .positiveText(R.string.positive)
                        .show();
                break;
            case R.id.buttonfeedback:
                new MaterialDialog.Builder(this.getSceneContext())
                        .title(R.string.feed_back_dialog_title)
                        .content("Thank you for your feedback regarding Pomodoro+, What you shared with me will help us to improve.\nThanks again")
                        .inputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE)
                        .input("", "", new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                String content = input.toString();
                                if (content.length() == 0) {
                                    return;
                                }
                                DBManager.commitFeedBack(content, new DBManager.DBApiCallBack<DocumentReference>() {
                                    @Override
                                    public void onResponse(ArrayList<DocumentReference> models) {
                                        Toast.makeText(getSceneContext(), "Feed back success", Toast.LENGTH_LONG).show();
                                    }

                                    @Override
                                    public void onError(Exception error) {
                                        Toast.makeText(getSceneContext(), "Failed to upload feed back", Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        }).show();
                break;
            case R.id.buttonhelp:
                Uri uri = Uri.parse ("mailto: ywang537@hawk.iit.edu");
                Intent intent = new Intent (Intent.ACTION_SENDTO, uri);
                main.startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public void update(Observable observable, Object o) {
        if (o instanceof FirebaseUser) {
            FirebaseUser user = (FirebaseUser)o;
            me = user;
            updateLoginStatus(true);
        } else {
            me = null;
            updateLoginStatus(false);
        }
    }
}